package com.yitiao.multithread.completablefuture;

import java.util.concurrent.*;

public class MyFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        extracted();

        // 回归生活，应该是子线程完成任务后主动通知主线程，我干完了 -- 异步回调（MQ思想）
        // 对于有关联的多个任务，如何编排，比如 买菜，买油，买锅，都完成了一起通知
        // 或任务间互相依赖，比如下单，扣库存，发货
        // 等等复杂的任务，如何处理 -- 升级future
        // coding

        // runAsync 无返回值
        final CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("---------come in");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 11;
        }).thenApply(f->{
            return f+2;
        }).whenComplete((v,e)->{
            if (e==null){
                System.out.println("v-----"+v);
            }
        }).exceptionally(e->{
            System.out.println(e);
            return null;
        });

        System.out.println("main over");
        TimeUnit.SECONDS.sleep(5);


//        final ExecutorService threadPool = Executors.newFixedThreadPool(10);
//
//        final CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
//            System.out.println("---------come in thread pool");
//            try {
//                TimeUnit.SECONDS.sleep(3);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return 12;
//        }, threadPool);
//
//        threadPool.shutdown();

    }

    private static void extracted() throws InterruptedException, ExecutionException {
        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println(Thread.currentThread().getName()+"  Thread-name");
            TimeUnit.SECONDS.sleep(1);

            return 1024;
        });

        new Thread(task,"t1").start();

        // get会阻塞，推荐放在最后
        // 可是设置超时时间，抛出异常
        // 用轮训代替阻塞  -- 但依然耗费资源
        try {
            System.out.println(task.get(2,TimeUnit.SECONDS));

        }catch (TimeoutException e){
            System.out.println(e.toString());
        }finally {
            System.out.println("过时不候");
        }
    }
}
